package com.david.webtest.blog

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.david.webtest.WebApplication
import com.david.webtest.R
import com.david.webtest.utils.PreferenceUtils

class BlogAdapter: RecyclerView.Adapter<BlogAdapter.BlogHolder>(), View.OnClickListener {
    var list:ArrayList<BlogBean> = ArrayList()
    set(value) {
        field = value
        notifyDataSetChanged()
    }

    override fun onClick(view: View?) {
        if (view == null) {
            return
        }
        if (view.id == R.id.item_blog_list_title) {
            onBlogItemClickListener?.onBlogItemClick(view.tag as String)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BlogHolder {
        return BlogHolder(LayoutInflater.from(WebApplication.instance).inflate(R.layout.item_blog_list, parent, false))
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: BlogHolder, position: Int) {
        if (TextUtils.isEmpty(list[position].name) || list[position].name.startsWith("http")) {
            holder.title.text = PreferenceUtils.getInstance().getBlogName(list[position].url)
        } else {
            holder.title.text = list[position].name
        }
        holder.title.tag = list[position].url
    }

    inner class BlogHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
        var title:TextView = itemView as TextView
        init {
            title.setOnClickListener(this@BlogAdapter)
        }
    }

    var onBlogItemClickListener:OnBlogItemClickListener? = null

    interface OnBlogItemClickListener{
        fun onBlogItemClick(url:String)
    }
}